(ns ura.Auth
  (:require
   [reagent.core :as r]
   [reagent.dom :as rd]
   [re-frame.core :as fc]
   [stylefy.core :as sty]
   [stylefy.reagent :as stylefy-reagent]
   [ajax.core :refer [GET POST PUT DELETE]]
   [ura.common :as uc :refer [log spy]]
   [ura.config :refer [getUrl]]
   [ura.ui :as ui]
   [ura.table :refer [MyTable]]
   [ura.style :refer [attr]]

   ["antd" :as ant]

   [re-com.core :as rc :refer [at]]
   ))

(def tableData (r/atom {:data []}))
(def editModal (r/atom false))
(def dataItem (r/atom nil))

(defn loadData [& param]
  (let [p (js->clj param)]
    (log "Auth.cljs query auth data " p)
    (GET (getUrl "/ura/auth")
         {:params p
          :response-format :json
          :keywords? true
          :handler
          (fn [resp]
            (log "get auth resp " resp)
            (swap! tableData assoc :data resp)
            )
          })
    )
  )

(defn saveItem [data]
  (let [method (if (nil? data.id) POST PUT)]
    (log "save auth data " method data)
    (method (getUrl "/ura/auth")
            {
             :headers {:content-type "application/json"}
             :body (js/JSON.stringify (clj->js data))
             :handler (fn [resp]
                        (log " authInfo " resp)
                        )
             :error-handler (fn [resp]
                              (log "error " resp)
                              ;; TODO show erro message
                              )
             :finally (fn []
                        (reset! dataItem nil)
                        (loadData)
                        )
             })
    )
  )

;;; ui

(defn confirmForm []
  ;; do validate
  (reset! editModal false)
  (saveItem @dataItem)
  )

(defn editModel []
  (fn []
    (when @editModal 
    [rc/modal-panel {:src (rc/at)
                     :backdrop-on-click #(reset! editModal nil)
                     :child [:div.box {}
                             [:span "添加权限"]
                             [:div
                              [ui/MyFormField {:label "分组" :required true}
                               [ui/MyInput {:model (r/cursor dataItem [:category])} ]
                               ]
                              [ui/MyFormField {:label "名称" :required true}
                               [ui/MyInput {:model (r/cursor dataItem [:name])} ]
                               ]
                              [ui/MyFormField {:label "编码" :required true}
                               [ui/MyInput {:model (r/cursor dataItem [:code])} ]
                               ]
                              [ui/MyFormField {:label "说明" :required true}
                               [ui/MyInput {:model (r/cursor dataItem [:description])} ]
                               ]
                              ]
                             [:div (attr :flex :jc-e :gap=15)
                              [:button.btn {:on-click #(reset! editModal nil)} "取消"]
                              [:button.btn.btn-primary {:on-click confirmForm} "确定"]
                              ]
                             ]}])))


(defn handleEdit [rowData]
  (log "handle edit event: " rowData)
  ;; validate
  (reset! dataItem rowData)
  (reset! editModal true)
  )

;; Top tool bar

(defn searchForm []
  (let [searchParam (r/atom {})]
    (fn []
      [:div (attr :flex :gap=10)
       [ui/my-label {} "名称："]
       [ui/MyInput {:model (r/cursor searchParam [:name])}]

       [ui/my-label {} "编码："]
       [ui/MyInput {:model (r/cursor searchParam [:code])}]
       
       [:button.btn.btn-primary (attr {:on-click #(loadData @searchParam)})
        [:i.fa.fa-search (attr :mr=5)] "查询"]
       [:button.btn.btn-primary (attr {:on-click #(do (reset! searchParam {}) (loadData))})
        [:i.fa.fa-rotate-right (attr :mr=5)] "重置"]
       ]
      )
    )
  )

(defn topBar []
  [ui/my-toolbar (attr :jc-b)
   [:button.btn.btn-primary {:on-click #(
                                         (reset! dataItem {})
                                         (reset! editModal true))
                             } [:i.fa.fa-plus (attr :mr=5)] "添加权限"]
   [searchForm]
   ]
  )

(defn handleSelect [keys rows]
  (let [selected (js->clj rows :keywordize-keys true)]
    )
  )


(defn callDelete [data]
  (log "call delete " data)
  (DELETE (getUrl (str "/ura/auth/" (:id data)))
          {:handler (fn [resp]
                      (loadData)
                      (log "delete auth data" resp)
                      )
           }))


(defn datatable []
  [:div
   [:> ant/Table
    {
     :dataSource @(r/cursor tableData [:data])
     :rowClassName (fn [record index] (if (== 0 (mod index 2)) "tableStriped" ""))
     :row-key "id"
     :size "small"
     :stripe "true"
     :columns [
               {:title "编号" :dataIndex "id"}
               {:title "分组" :dataIndex "category" :sorter #(uc/comparison %1 %2 :category)}
               {:title "名称" :dataIndex "name" :sorter #(uc/comparison %1 %2 :name)}
               {:title "编码" :dataIndex "code" :sorter #(uc/comparison %1 %2 :code)}
               {:title "说明" :dataIndex "description"}
               {:title "Actions" :width "220px"
                :render (fn [value0 record0 index]
                          (let [value (js->clj value0 {:keywordize-keys true})
                                ]
                          (r/as-element 
                           [:div (attr :flex :gap=10)
                            [:> ant/Popconfirm {:title "是否删除数据？"
                                                :description (:name value)
                                                :onConfirm #(callDelete value)
                                                :okText "删除"
                                                :cancelText "不删除"
                                                }
                             [:> ant/Button {:size "small" :danger true} "删除"]]
                            [:> ant/Button {:size "small" 
                                            :on-click #(handleEdit value)} "编辑"]
                            ]
                           )))}
               ]
     :pagination {:show-size-changer true 
                  :page-size-options ["5" "10" "20" "50"]
                  :show-total #(str "总计: " % "数据")}
     }]
   ]
  )

(defn genPage []
  (loadData)
  [:div
   [editModel]
   [topBar]
   [datatable]
   ]
)
